import styles from '../index.less';
import React, { useState, useEffect, useRef } from 'react';
import kls from 'classnames';
import { Table, Select } from 'antd';
import SafeRateChart from './chart1';
import { useSelector, useDispatch } from 'umi';
import { listAllSafetyIndex, listSafetyIndexById } from '@/services/bimServices';
import { useEffectOnce } from 'react-use';
import useLayer, { REAL_LYR_TYPE } from './use-layer';
import useHighlight from './use-highlight';
import { jsapi, viewUtils } from '@/utils/arcgis';

const { Option } = Select;

const LAYER_TAG = '安全轨迹';

export const colorList = [
  '#233c4c',
  '#FE6751',
  '#2FB0FF',
  '#3D98FF',
  '#3DFF9F',
  '#9EFF3D',
  '#E83DFF',
];

function getUniqueLineSymbol(color) {
  return {
    type: 'simple-line', // autocasts as new SimpleLineSymbol()
    color,
    width: 4,
    style: 'solid',
  };
}
const lineSymbol = getUniqueLineSymbol(colorList[0]);

const columns = [
  {
    title: '负责人',
    dataIndex: 'title',
    // width: '80px',
    align: 'left',
    // ellipsis: true,
    render: (data, record) => {
      return record[0].responsibleName || '--';
    },
  },
  // { title: '名称', dataIndex: 'title', width: '80px', align: 'left', ellipsis: true },
  {
    title: '时间',
    dataIndex: 'time',
    align: 'right',
    // ellipsis: true,
    render: (data, record) => {
      return record[0].belongDateString || '--';
    },
  },
];

const Right = () => {
  const dispatch = useDispatch();
  const curProjId = useSelector(s => s.app.curProjId);
  const dangerSourceExamine = useSelector(s => s.projectPage.dangerSourceExamine);
  const [last30DayData, setLast30DayData] = useState([]);
  const [projInfo, setProjInfo] = useState({ total: 0, index: 1, percent: 0 });
  const [curRouterIndex, setCurRouterIndex] = useState(0);
  const [gotoIndex, setGotoIndex] = useState(0);
  const legendRef = useRef(null);
  const legendInstance = useRef(null);
  const [legendRefresh, setLegendRefresh] = useState(1);
  const [dangerLyr, { hideLayer, showLayer, setLayer, reLaunchLayer }] = useLayer(null);
  const [setHighlight, clearHighlight] = useHighlight();
  const searchStr = `?projectId=${curProjId}`;
  useEffectOnce(() => {
    dispatch({
      type: 'projectPage/listDangerSourceExamine',
    });
  });

  useEffect(() => {
    if (!dangerLyr) {
      return;
    }

    window.agsGlobal.view.goTo(dangerLyr.source._items[gotoIndex].geometry);
    setHighlight(dangerLyr, dangerLyr.source._items[gotoIndex]);
  }, [gotoIndex, dangerLyr]);

  useEffect(() => {
    if (!dangerSourceExamine.length) {
      return;
    }
    handleLayerDataChange(dangerSourceExamine[curRouterIndex]);

    return () => {
      hideLayer();
    };
  }, [curRouterIndex, dangerSourceExamine]);

  async function handleLayerDataChange(data) {
    setLegendRefresh(e => e + 1);
    const [Graphic] = await jsapi.load(['esri/Graphic']);
    const graphics = data.locationList.map(item => {
      const { paths, rawData } = item.reduce(
        (r, e) => {
          r.paths.push([e.longitude, e.latitude]);
          if (r.rawData) {
            r.rawData = e;
          }
          return r;
        },
        { paths: [], rawData: {} },
      );

      let cfg = {
        geometry: {
          type: 'polyline', // autocasts as new Polyline()
          paths: paths,
        },
        symbol: lineSymbol,
        attributes: rawData,
      };
      return new Graphic(cfg);
    });

    // 因为自定义的graphicLayer无法动态动态修改
    const lyr = await reLaunchLayer({
      title: LAYER_TAG,
      type: REAL_LYR_TYPE.FeatureLayer,
      source: graphics,
      objectIdField: 'OBJECTID',
      fields: [
        {
          name: 'OBJECTID',
          type: 'oid',
        },
        {
          name: 'responsibleName',
          type: 'string',
        },
        {
          name: 'belongDateString',
          type: 'string',
        },
        {
          name: 'phone',
          type: 'string',
        },
      ],
      //todo 动态生成uniqueValueInfos
      renderer: {
        type: 'unique-value', // autocasts as new UniqueValueRenderer()
        defaultSymbol: lineSymbol,
        defaultLabel: '其他主要线路',
        field: 'belongDateString',
        uniqueValueInfos: graphics.map((e, i) => {
          return {
            value: e.attributes.belongDateString, // code for interstates/freeways
            label: e.attributes.belongDateString,
            symbol: getUniqueLineSymbol(colorList[i]),
          };
        }),
      },
      popupTemplate: {
        title: `${LAYER_TAG}   {belongDateString}`,
        content: [
          {
            type: 'fields',
            fieldInfos: [
              {
                fieldName: 'responsibleName',

                label: '负责人',
              },
              {
                fieldName: 'belongDateString',

                label: '日期',
              },
              {
                fieldName: 'phone',

                label: '联系方式',
              },
            ],
          },
        ],
      },
    });
    if (legendInstance.current) {
      legendInstance.current.destroy();
    }
    legendInstance.current = await setLegend(lyr);
  }

  async function setLegend(layer) {
    if (!legendRef.current) {
      return;
    }
    const view = await viewUtils.isViewReady();
    const [Legend] = await jsapi.load(['esri/widgets/Legend']);
    let result = new Legend({
      view: view,
      container: legendRef.current,
      layerInfos: [
        {
          layer: layer,
          title: '安全轨迹',
        },
      ],
    });
    // console.log(result);

    return result;
  }

  useEffect(() => {
    if (curProjId) {
      listAllSafetyIndex().then(data => {
        const total = data.length;
        let index = 1;
        let percent = 100;
        let sortData = data.sort((a, b) => b.safeProduceIndex - a.safeProduceIndex);
        for (let i = 0; i < sortData.length; i++) {
          const item = sortData[i];
          if (item.projectId == curProjId) {
            index = i + 1;
            percent = (item.safeProduceIndex * 100).toFixed();
            break;
          }
        }
        setProjInfo({
          total,
          index,
          percent,
        });
      });
      listSafetyIndexById(curProjId).then(data => {
        setLast30DayData(data);
        // {
        //   "belongDate": "2021-06-03",
        //   "safeProduceIndex": 0.77
        // },
      });
    }
  }, [curProjId]);

  return (
    <div className={kls(styles.qualityAndSafetyR)}>
      <div className="side-panel2" style={{ top: 144, right: 24 }}>
        <div className="side-panel2-title  flex-spb">
          安全巡检
          <a
            href={'http://wccg.tech:82/#/safeScheme/dangerSourceSafeExamineDailyTotal' + searchStr}
            target="_blank"
            rel="noreferrer"
          >
            查看详情
          </a>
        </div>
        <div
          className={kls('side-panel2-body', styles.autoHeightPanel)}
          style={{ paddingRight: 16 }}
        >
          <div className={kls(styles.rate)}>
            {/* <p>安全文明生产指数</p> */}
            <div className="side-panel2-subtitle"> 安全文明生产指数</div>
            <div className="flex-spb">
              <div className={kls(styles.bar)} style={{ backgroundSize: projInfo.percent + '%' }}>
                {'▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌'}{' '}
              </div>
              <div className={kls(styles.num)}>{projInfo.percent}</div>
            </div>
            <div className={kls(styles.info, 'flex-spb')}>
              安全文明生产排名
              <span>{`${projInfo.index}/${projInfo.total}`}</span>
            </div>
          </div>

          <p className={kls('side-panel2-subtitle')}>安全生产指数曲线图</p>
          <SafeRateChart last30DayData={last30DayData} />

          <div className="side-panel2-subtitle"> 近一周巡检路线</div>
          {/* <div className={kls(styles.blockTitle, 'flex-spb')} style={{ marginBottom: 2 }}>
            近一周巡检路线
          </div> */}
          <Select
            value={curRouterIndex}
            size={'small'}
            style={{ marginRight: 10, marginBottom: 16 }}
            onChange={e => setCurRouterIndex(e)}
          >
            {!!dangerSourceExamine.length &&
              dangerSourceExamine.map(({ wbsCode }, i) => {
                return (
                  <Option key={wbsCode} value={i}>
                    {wbsCode}
                  </Option>
                );
              })}
          </Select>
          <Table
            columns={columns}
            dataSource={
              dangerSourceExamine && dangerSourceExamine.length
                ? dangerSourceExamine[curRouterIndex].locationList
                : []
            }
            rowKey={'belongDateString'}
            size={'small'}
            style={{ width: '360px' }}
            onRow={(record, index) => {
              return {
                onClick: event => {
                  // console.log(record, rest);
                  setGotoIndex(index);
                },
              };
            }}
            pagination={{ pageSize: 10, hideOnSinglePage: true }}
          />
        </div>
      </div>
      <div
        key={legendRefresh}
        ref={legendRef}
        className={kls('base-panel-body', styles.legend)}
        style={{
          position: 'fixed',
          bottom: 68,
          right: 466,
          color: '#fff',
        }}
      ></div>
    </div>
  );
};

export default Right;
